package com.tianji.learning.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.api.client.user.UserClient;
import com.tianji.common.exceptions.DbException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.ReplyDTO;
import com.tianji.learning.enums.QuestionStatus;
import com.tianji.learning.mapper.InteractionQuestionMapper;
import com.tianji.learning.mapper.InteractionReplyMapper;
import com.tianji.learning.model.po.InteractionQuestion;
import com.tianji.learning.model.po.InteractionReply;
import com.tianji.learning.service.IInteractionReplyService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 互动问题的回答或评论 服务实现类
 * </p>
 *
 * @author AvA
 * @since 2024-12-27
 */
@Service
@RequiredArgsConstructor
public class InteractionReplyServiceImpl extends ServiceImpl<InteractionReplyMapper, InteractionReply> implements IInteractionReplyService {

    private final InteractionQuestionMapper questionMapper;

    private final UserClient userClient;

    @Override
    public void addReplyOrAnswer(ReplyDTO dto) {
        //1.获取用户
        Long user = UserContext.getUser();
        //2.保存回答或评论
        InteractionReply reply = BeanUtils.copyBean(dto, InteractionReply.class);
        reply.setUserId(user);
        InteractionQuestion question = questionMapper.selectById(dto.getQuestionId());
        boolean save = save(reply);
        if (!save) {
            throw new DbException("数据库保存该回答/评论失败");
        }
        //3.判断是评论还是回答
        //3.1是回答
        if (dto.getAnswerId() == null && dto.getTargetReplyId() == null) {
            //更新AnswerId为0并累计回答次数
            question.setAnswerTimes(question.getAnswerTimes() + 1);
            question.setLatestAnswerId(reply.getId());
        } else {
            //3.2是评论
            //更新被评论对象的被评论次数
            InteractionReply byId = getById(dto.getAnswerId());
            byId.setReplyTimes(byId.getReplyTimes() + 1);
            updateById(byId);
        }
        //4.是学生，则更新该问题状态为未查看(提醒老师该问题有新的回答)
        if (dto.getIsStudent()) {
            question.setStatus(QuestionStatus.UN_CHECK);
            questionMapper.updateById(question);
        }
    }
}
